// 内核内存管理 - 物理内存和虚拟内存

/// 物理页大小
pub const PAGE_SIZE: usize = 4096;

/// 物理内存分配器（位图方式）
pub const PhysicalAllocator = struct {
    bitmap: [*]u8,
    total_pages: usize,
    used_pages: usize,
    
    pub fn init(memory_start: usize, memory_size: usize) PhysicalAllocator {
        const total_pages = memory_size / PAGE_SIZE;
        const bitmap_size = (total_pages + 7) / 8;
        
        return .{
            .bitmap = @ptrFromInt(memory_start),
            .total_pages = total_pages,
            .used_pages = 0,
        };
    }
    
    pub fn alloc_page(self: *PhysicalAllocator) ?usize {
        var i: usize = 0;
        while (i < self.total_pages) : (i += 1) {
            const byte_idx = i / 8;
            const bit_idx = @as(u3, @intCast(i % 8));
            
            if ((self.bitmap[byte_idx] & (@as(u8, 1) << bit_idx)) == 0) {
                // 找到空闲页
                self.bitmap[byte_idx] |= (@as(u8, 1) << bit_idx);
                self.used_pages += 1;
                return i * PAGE_SIZE;
            }
        }
        
        return null; // 内存不足
    }
    
    pub fn free_page(self: *PhysicalAllocator, addr: usize) void {
        const page_idx = addr / PAGE_SIZE;
        const byte_idx = page_idx / 8;
        const bit_idx = @as(u3, @intCast(page_idx % 8));
        
        self.bitmap[byte_idx] &= ~(@as(u8, 1) << bit_idx);
        self.used_pages -= 1;
    }
};

/// 简单的堆分配器（用于内核）
pub const KernelHeap = struct {
    start: usize,
    end: usize,
    current: usize,
    
    pub fn init(start: usize, size: usize) KernelHeap {
        return .{
            .start = start,
            .end = start + size,
            .current = start,
        };
    }
    
    pub fn alloc(self: *KernelHeap, size: usize, alignment: usize) ?[*]u8 {
        // 对齐
        const aligned = (self.current + alignment - 1) & ~(alignment - 1);
        const new_current = aligned + size;
        
        if (new_current > self.end) {
            return null; // 堆空间不足
        }
        
        self.current = new_current;
        return @ptrFromInt(aligned);
    }
    
    // 简单实现：不支持 free（使用 Arena 模式）
    pub fn reset(self: *KernelHeap) void {
        self.current = self.start;
    }
};

/// Actor 专用内存池
pub const ActorMemoryPool = struct {
    pools: [64]KernelHeap,
    
    pub fn init(base_addr: usize) ActorMemoryPool {
        var self: ActorMemoryPool = undefined;
        
        var i: usize = 0;
        while (i < 64) : (i += 1) {
            const pool_start = base_addr + i * 64 * 1024; // 每个 Actor 64KB
            self.pools[i] = KernelHeap.init(pool_start, 64 * 1024);
        }
        
        return self;
    }
    
    pub fn get_pool(self: *ActorMemoryPool, actor_id: u32) *KernelHeap {
        return &self.pools[actor_id];
    }
};
